package com.ash.nio.tcp.chat;

import com.ash.nio.BuffUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class ChatCli {

    public static void main(String[] args) throws IOException {
        System.out.println("请求输入用户名称:");
        Scanner scanner = new Scanner(System.in);

        String useName = scanner.nextLine();


        SocketChannel socketChannel = SocketChannel.open();

        // 这两行代码不能换位置 会出问题，导致报NotYetConnectedException异常
        socketChannel.connect(new InetSocketAddress(8081));
        socketChannel.configureBlocking(false);

        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);


        new Thread(() -> {
            try {
                while (true) {
                    handleEvent(selector);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();


        while (true) {
            String msg = scanner.nextLine();
            msg = useName + "说:" + msg;
            socketChannel.write(ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)));
        }


    }

    private static void handleEvent(Selector selector) throws IOException {
        int select = selector.select();
        if (select <= 0) {
            return;
        }

        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey selectionKey = iterator.next();

            if (selectionKey.isReadable()) {
                SocketChannel channel = (SocketChannel) selectionKey.channel();

                ByteBuffer allocate = ByteBuffer.allocate(1024);
                channel.read(allocate);

                System.out.println(BuffUtil.byteBuffString(allocate));
            }

            iterator.remove();
        }
    }
}
